<template>
  <div class="max-1200" v-if="windowWidth>992">
    <div id="crumbs" class="max-1200">
      <img src="@/assets/icon/weizhi.png" alt="" class="ic"/>

      <a href="/admin">{{ globalLanguage.languageSuffix == 'Cn' ? '首页' : 'Главная страница' }}</a> &gt;
      <router-link to="/new"> {{
          globalLanguage.languageSuffix === "Cn"
              ? "新闻公共"
              : "Общественная информация"
        }}
      </router-link>

    </div>
    <div style="display: flex; flex-wrap: wrap">
      <el-card style="width: 198px;height: 240px; margin: 33px 20px 20px 20px; " @click="centerDialogVisible = true">
        <!--       添加圆形按钮-->
        <div
            style="margin: 40px auto; width: 100px; height: 100px; border-radius: 50%;background-color: #409eff;text-align: center;">
          <el-icon style="width: 100px; height: 100px;">
            <Plus/>
          </el-icon>
          <p>添加</p>
        </div>
      </el-card>
      <el-dialog v-model="centerDialogVisible" title="Warning" width="800" center>
        <span center>添加新闻</span>
        <template #footer>
          <div class="dialog-footer">
            <el-form :model="caseForm" :rules="rules" ref="caseFormRef" label-width="140px">
              <el-form-item label="新闻标题中文名称" prop="titleCn">
                <el-input v-model="caseForm.titleCn"></el-input>
              </el-form-item>
              <el-form-item label="新闻标题俄文名称" prop="titleRa">
                <el-input v-model="caseForm.titleRa"></el-input>
              </el-form-item>
              <el-form-item label="新闻图片">
                <el-upload
                    class="upload-btn"
                    :action="`${apiUrl}/news/handleImage`"
                    :show-file-list="false"
                    :on-success="handleSuccess"
                    :before-upload="beforeUpload"
                >
                  <el-button size="small" type="primary" style="width: 50px;">上传图片</el-button>
                </el-upload>
                <!-- 添加显示上传图片的元素 -->
                <div v-if="uploadedImgUrl">
                  <img :src="isHttp(uploadedImgUrl)" alt="Uploaded Image" style="max-width: 100%; height: auto;"/>
                </div>
              </el-form-item>
              <el-form-item label="新闻详情中文" prop="descCn">
                <el-input type="textarea" :rows="6" cols="50" v-model="caseForm.descCn"></el-input>
              </el-form-item>
              <el-form-item label="新闻详情俄文" prop="descRa">
                <el-input type="textarea" :rows="6" cols="50" v-model="caseForm.descRa"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="addnews">添加</el-button>
              </el-form-item>
            </el-form>
          </div>
        </template>
      </el-dialog>
      <div style=" width: 20%;padding: 0 20px; margin-top: 30px; margin-bottom: 20px; " v-for="item in newsList"
           :key="item">
        <!--        <el-card @click="navigateToDetails(item.id)">
                  <img
                    :src="isHttp(item.imgUrl)"
                    class="image"
                    width="100%"
                    height="150px"
                  />
                  <div style="margin-top: 20px; height: 30px">
                    <span>{{ item["title" + globalLanguage.languageSuffix] }}</span>
                  </div>
                </el-card>-->
        <el-card @click="navigateToDetails(item.id)">
          <img
              :src="isHttp(item.imgUrl)"
              class="image"
              width="100%"
              height="150px"
          />
          <div style="margin-top: 20px; height: 30px;padding: 0 10px">
            <span>{{ item['title' + globalLanguage.languageSuffix] }}</span>
          </div>
        </el-card>
      </div>
    </div>
  </div>
  <div class="mbphone" v-else>
    <!--面包屑 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/admin' }">{{ globalLanguage.languageSuffix === 'Cn' ? '首页' : 'главная' }}
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{
          globalLanguage.languageSuffix === 'Cn' ? '新闻公共' : 'Новостное объявление'
        }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="news" @scroll="handleScroll1">
      <div class="tupian">
        <el-card v-for="news in newsList.records" class="news-card" :key="news.id" @click="navigateToDetails(news.id)"
                 v-if="news.id !==null  && news.id !== ''">
          <div class="image-container">
            <img
                :src="isHttp(news.imgUrl)"
            />
          </div>
          <template #footer>{{ globalLanguage.languageSuffix === 'Cn' ? news.titleCn : news.titleRa }}</template>
        </el-card>
      </div>
      <div v-if="loading" class="loading-spinner">加载中...</div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import {listNewsPage, listNews, addNews} from "@/api/news.js";
import {useRouter} from "vue-router";
import '@/style.css'
import {isHttp} from "@/utils/index.js";
import {ElMessage} from "element-plus";
const apiUrl = ref(import.meta.env.VITE_APP_BASE_API);

const page = ref({
  pageNo: 1,
  pageSize: 10,
});
const caseFormRef = ref(null);
const rules = {
  titleCn: [
    {required: true, message: '请输入新闻标题中文名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'},
  ],
  titleRa: [
    {required: true, message: '请输入新闻标题俄文名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'},
  ],
  descCn: [
    {required: true, message: '请输入新闻详情中文', trigger: 'blur'},
    {min: 2, max: 2000, message: '长度在 2 到 2000 个字符', trigger: 'blur'},
  ],
  descRa: [
    {required: true, message: '请输入新闻详情俄文', trigger: 'blur'},
    {min: 2, max: 2000, message: '长度在 2 到 2000 个字符', trigger: 'blur'},
  ],
};
//添加新闻
const caseForm = ref({
  titleCn: '',
  titleRa: '',
  imgUrl: '',
  descCn: '',
  descRa: '',
});
// 关闭弹窗
const closeDialog = () => {
  centerDialogVisible.value = false;
  //清空表单
  caseForm.value = {
    titleCn: '',
    titleRa: '',
    imgUrl: '',
    descCn: '',
    descRa: '',
  };
}
const uploadedImgUrl = ref('');// 用于存储上传后的图片URL
const centerDialogVisible = ref(false);
const total = ref(0);
const newsList = ref({total: 0, records: []});
const loading = ref(false);
const windowWidth = ref(window.innerWidth); // 用于判断当前窗口宽度
const loadNews = async () => {
  const res = await listNewsPage(page.value);
  if (res.code === 200) {
    newsList.value = res.newsIPage.records;
    total.value = res.newsIPage.total;
  }
};
/*不分页查询所有*/
const allNews = async () => {
  const res = await listNews();
  if (res.code === 200) {
    newsList.value = res.newsList;
  }
}
//上传成功后回调
const handleSuccess = (response, file) => {
  console.log('上传成功的响应:', response);
  console.log('上传的文件信息:', file); // 查看文件信息
  if (response && response.url) {
    uploadedImgUrl.value = response.url; // 更新logo为上传成功的图片URL
    console.log('更新后的uploadedImgUrl:', uploadedImgUrl.value); // 查看更新后的logo
  }
};
// 在上传前检查文件的有效性
const beforeUpload = (file) => {
  console.log('准备上传的文件:', file); // 输出文件信息
  const isImage = file.type.startsWith('image/');
  console.log('是否是图片文件:', isImage);
  if (!isImage) {
    console.log('只能上传图片文件！');
    this.$message.error('上传的文件必须是图片！');
    return false; // 阻止上传
  }
  return true; // 继续上传
};
//添加新闻
const addnews = async () => {
  // 触发表单校验
  await caseFormRef.value.validate(async (valid) => {
    if (valid) {
      if (uploadedImgUrl.value) {
        //将uploadImgUrl的值赋值给imgUrl
        caseForm.value.imgUrl = uploadedImgUrl.value;
      }
      const res = await addNews(caseForm.value);
      if (res.code === 200) {
        ElMessage.success('添加新闻成功');
        centerDialogVisible.value = false;
        //清空表单
        caseForm.value = {
          titleCn: '',
          titleRa: '',
          imgUrl: '',
          descCn: '',
          descRa: '',
        };
        // 刷新页面
        allNews();
      } else {
        ElMessage.error('添加新闻失败');
      }
    } else {
      console.log('表单校验失败');
      ElMessage.error('请填写正确的表单信息');
      return false;
    }
  });

}

const handleResize = () => {
  windowWidth.value = window.innerWidth;
  if (windowWidth.value <= 992) {
    // 重置页码为1，因为可能需要重新加载第一页的数据
    news(); // 调用news函数重新加载数据
  }
};
onMounted(() => {
  allNews(); // 初始化加载数据
  news(); // 初始加载数据
  windowWidth.value = window.innerWidth;
  window.addEventListener('resize', handleResize);
  /*滚动分页*/
  window.addEventListener('scroll', handleScroll1);
});
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  // 移除监听
  window.removeEventListener('scroll', handleScroll1);
});
const router = useRouter();
const navigateToDetails = (id) => {
  // 使用路由参数导航
  router.push({name: "newsDetail", query: {id: id}});
};
const news = async () => {
  if (loading.value) return; // 防止重复请求
  loading.value = true;
  //获取在宽度大于992px的情况下的pageNO
  if (windowWidth.value <= 992) {
    page.value.pageNo = 1; // 重置页码
  }
  console.log("当前页码 :", page.value.pageNo)
  const res = await listNewsPage(page.value);
  console.log("新闻列表数据 :", res.newsIPage)
  if (res.code === 200) {
    if (!Array.isArray(newsList.value.records)) {
      newsList.value.records = []; // 如果未定义，则初始化为一个空数组
    }
    // 合并新获取的数据
    newsList.value.records = newsList.value.records.concat(res.newsIPage.records || []);
    total.value = parseInt(res.newsIPage.total);
    page.value.pageNo++;   // 页码加1
  }
  loading.value = false;
};

/*滚动分页*/
const handleScroll1 = () => {
  if (!newsList.value || !newsList.value.records) return; // 确保 Newslist 正确初始化
  const scrollTop = window.scrollY || document.documentElement.scrollTop;
  const windowHeight = window.innerHeight;
  const documentHeight = document.documentElement.scrollHeight;
  if (scrollTop + windowHeight >= documentHeight - 100) { // 到达底部
    if (newsList.value.records.length < total.value) {
      news(); // 加载更多内容
    }
  }
}

</script>

<style scoped>
.mbphone {
  margin-top: -65px !important; /* 距离顶部87.5px */
}

.breadcrumb {
  position: fixed; /* 固定在视口 */
  top: 87.5px; /* 距离顶部0 */
  left: 0; /* 距离左侧0 */
  right: 0; /* 距离右侧0 */
  background: white; /* 背景色 */
  z-index: 10; /* 确保在其他内容之上 */
  padding: 20px; /* 添加内边距 */
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
  padding: 5px;
  width: 100%;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
  width: 100%;
}

.news {
  padding-top: 70px; /* 根据面包屑的高度添加相应的内边距 */
  width: 100%;
  height: 100%;
  overflow: auto; /* 添加滚动条 */
}

.tupian {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap; /* 允许换行 */
  margin-bottom: 10px;
}

.news-card {
  width: 48%; /* 设置为48%以避免换行时的间距问题 */
  margin-bottom: 10px; /* 控制每个卡片之间的间距 */
}

.image-container {
  display: flex; /* 使外层容器是flexbox */
  align-items: center; /* 垂直居中图片 */
  justify-content: center; /* 水平居中图片 */
  height: 100px; /* 设置固定高度 */
  width: 100%; /* 填满父容器的宽度 */
}

.news-card img {
  height: 100px !important;
  width: 100%; /* 或设置为具体值，例如 100% */
  object-fit: fill; /* 填充整个img元素，可能剪裁cover */
}

.loading-spinner {
  text-align: center;
  margin: 20px 0;
}

</style>
